package com.party.mobile.web.controller.gatherInfo;

import com.google.common.base.Strings;
import com.party.api.dto.idcard.request.IdcardVerifyRequest;
import com.party.api.dto.idcard.response.IdcardVerifyResult;
import com.party.api.service.idcard.IIdcardVerifyService;
import com.party.authorization.annotation.Authorization;
import com.party.common.constant.Constant;
import com.party.common.redis.StringJedis;
import com.party.common.utils.DateUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.gatherInfo.GatherInfoMember;
import com.party.core.model.gatherInfo.GatherInfoProject;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberInfo;
import com.party.core.model.member.PartnerMember;
import com.party.core.model.system.SysConfig;
import com.party.core.service.gatherInfo.IGatherInfoMemberService;
import com.party.core.service.gatherInfo.IGatherInfoProjectService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.member.IPartnerMemberService;
import com.party.core.service.member.biz.MemberPersonalCountBizService;
import com.party.core.service.system.ISysConfigService;
import com.party.mobile.biz.gatherInfo.GatherInfoMemberBizService;
import com.party.mobile.biz.member.MemberBizService;
import com.party.mobile.web.annotation.SessionToken;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.gatherInfo.input.GatherInfoMemberInput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import com.party.mobile.web.dto.login.output.MemberOutput;
import com.party.mobile.web.interceptor.TokenInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * 用户信息收集
 *
 * @author Administrator
 */
@Controller
@RequestMapping(value = "gatherInfo/member")
public class GatherInfoMemberController {
    @Value("#{apishow['apishow.appid']}")
    private String appid;
    @Value("#{apishow['apishow.appSecret']}")
    private String appSecret;

    @Autowired
    private StringJedis stringJedis;
    @Autowired
    private GatherInfoMemberBizService gatherInfoMemberBizService;
    @Autowired
    private IGatherInfoMemberService gatherInfoMemberService;
    @Autowired
    private MemberBizService memberBizService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private IPartnerMemberService partnerMemberService;
    @Autowired
    private IGatherInfoProjectService gatherInfoProjectService;
    @Autowired
    private MemberPersonalCountBizService memberPersonalCountBizService;

    @Autowired
    private IIdcardVerifyService iIdcardVerifyService;

    @Autowired
    private ISysConfigService sysConfigService;

    private final String ID_CARD_VERIFY_SWITCH = "IDCardVerifySwitch";

    @Resource
    TokenInterceptor tokenInterceptor;

    protected static Logger logger = LoggerFactory.getLogger(GatherInfoMemberController.class);

    /**
     * 获取基本信息
     *
     * @param projectId
     * @param request
     * @return
     * @throws Exception
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/getBaseInfo")
    public AjaxResult getBaseInfo(String projectId, HttpServletRequest request) throws Exception {
        // 数据验证
        if (Strings.isNullOrEmpty(projectId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "项目主键不能为空");
        }
        GatherInfoProject gatherInfoProject = gatherInfoProjectService.get(projectId);
        if (null == gatherInfoProject || gatherInfoProject.getDelFlag().equals("1")) {
            return AjaxResult.error(PartyCode.IS_NO_DATA, "文章内容不存在");
        }
        try {
            Map<String, Object> map = gatherInfoMemberBizService.getBaseInfo(projectId, request);
            AjaxResult ajaxResult = AjaxResult.success(map);
            tokenInterceptor.getToken(ajaxResult);
            return ajaxResult;
        } catch (Exception e) {
            logger.error("获取基本信息异常", e);
            return AjaxResult.error(100, "未知异常");
        }
    }

    /**
     * 基本信息收集
     *
     * @param member
     * @param verifyCode
     * @param projectId
     * @param request
     * @retur
     */
    @SessionToken(verify = true)
    @ResponseBody
    @Authorization
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = "/saveBaseInfo", method = RequestMethod.POST)
    public AjaxResult saveBaseInfo(Member member, MemberInfo memberInfo, String verifyCode, String projectId, HttpServletRequest request) {
        try {
            if (StringUtils.isEmpty(projectId)) {
                throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "项目id不能为空");
            }

            CurrentUser currentUser = memberBizService.bindPhoneBiz2(member.getMobile(), verifyCode, member.getCountryCode(), request);
            gatherInfoMemberBizService.saveBaseInfo(currentUser.getId(), member, memberInfo, request);
            MemberOutput memberOutput = memberBizService.getLoginMember(memberService.get(currentUser.getId()));

            gatherInfoMemberBizService.addMember(projectId, currentUser.getId());
            String partnerId = null;

            try {
                // 机构成员所属
                PartnerMember partnerMember = new PartnerMember();
                partnerId = gatherInfoProjectService.get(projectId).getCreateBy();
                partnerMember.setPartnerId(partnerId);
                partnerMember.setMemberId(currentUser.getId());
                partnerMemberService.getSet(partnerMember);
            } catch (Exception e) {
                logger.error("保存关系异常", e);
            }

            // 个人统计表添加数据
            try {
                memberPersonalCountBizService.getSet(partnerId, currentUser.getId());
            } catch (Exception e) {
                logger.error("个人统计表添加数据异常", e);
            }
            return AjaxResult.success(memberOutput);
        } catch (BusinessException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            AjaxResult ajaxResult = new AjaxResult();
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setErrorCode(e.getCode());
            ajaxResult.setDescription(e.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("保存基本信息失败：", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

            AjaxResult ajaxResult = new AjaxResult();
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setErrorCode(100);
            ajaxResult.setDescription("保存信息失败");
            return ajaxResult;
        }
    }

    /**
     * 获取保险信息
     *
     * @param request
     * @return
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/getInsuranceInfo")
    public AjaxResult getInsuranceInfo(String projectId, HttpServletRequest request) {
        // 数据验证
        if (Strings.isNullOrEmpty(projectId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "项目主键不能为空");
        }
        GatherInfoProject gatherInfoProject = gatherInfoProjectService.get(projectId);
        if (null == gatherInfoProject || gatherInfoProject.getDelFlag().equals("1")) {
            return AjaxResult.error(PartyCode.IS_NO_DATA, "文章内容不存在");
        }
        try {
            Map<String, Object> map = gatherInfoMemberBizService.getInsuranceInfo(projectId, request);
            AjaxResult ajaxResult = AjaxResult.success(map);
            tokenInterceptor.getToken(ajaxResult);
            return ajaxResult;
        } catch (Exception e) {
            logger.error("获取保险信息异常", e);
            return AjaxResult.error(100, "未知异常");
        }
    }

    /**
     * 保存保险信息
     *
     * @param memberInfo
     * @param member
     * @param verifyCode 手机验证码
     * @param request
     * @param carVerifyCode 身份证验证的时候输入的图形验证码
     * @return
     */
    @SessionToken(verify = true)
    @ResponseBody
    @Authorization
    @RequestMapping("saveInsuranceInfo")
    public AjaxResult saveInsuranceInfo(MemberInfo memberInfo, Member member, String verifyCode, String carVerifyCode, String projectId, HttpServletRequest request) {
        try {
            //输入证件的类型
            String type = memberInfo.getUseCertificate() + "";
            String idCard = memberInfo.getIdCard();
            if (type.equals("0")) {
                String birthStr = "";
                if (idCard.length() == 18) {
                    birthStr = idCard.substring(6, 10) + "-" + idCard.substring(10, 12) + "-" + idCard.substring(12, 14);
                }
                if (idCard.length() == 15) {
                    String headerDate = idCard.substring(6, 7);
                    if (headerDate.equals("9")) {
                        birthStr = "19" + idCard.substring(6, 8) + "-" + idCard.substring(8, 10) + "-" + idCard.substring(10, 12);
                    }
                }
                Date birthday = DateUtils.convertDate(birthStr);
                memberInfo.setBirthday(birthday);
            } else {
                String birthTime = memberInfo.getBirthdayTime();
                Date birthday = DateUtils.convertDate(birthTime);
                memberInfo.setBirthday(birthday);
            }
            CurrentUser currentUser = memberBizService.bindPhoneBiz2(member.getMobile(), verifyCode, member.getCountryCode(), request);
            //获取当前会员
            Member member1 = memberService.get(currentUser.getId());
            //  验证验证码
            String code = stringJedis.getValue(Constant.IDCARD_VERIFY_CODE + memberInfo.getIdCard());
            //如果输入的是身份证需要验证验证码

            if (type.equals("0") && member1.getIsCertified() == 0 && !carVerifyCode.equalsIgnoreCase(code)) {
                throw new BusinessException(100, "验证码错误");
            }

            member1.setCountryCode(member.getCountryCode());
            memberService.update(member1);

            // 2018/5/14 加验证开关，如果关，验证通过，状态为未验证
            SysConfig sysConfig = sysConfigService.findByCode(ID_CARD_VERIFY_SWITCH);
            if (Boolean.TRUE.toString().equals(sysConfig.getValue())) {
                //如果已验证则不需要身份认证
                //如果输入的是身份证，则进行身份证和名字验证
                if (type.equals("0") && member1.getIsCertified() == 0) {
                    //把身份证号码放进缓存
                    stringJedis.setValue(Constant.IS_NEED_IDCARD_VERIFY + memberInfo.getIdCard(), memberInfo.getIdCard());
                    IdcardVerifyRequest idcardVerifyRequest = new IdcardVerifyRequest();
                    idcardVerifyRequest.setIdcard(memberInfo.getIdCard());
                    idcardVerifyRequest.setName(member.getFullname());
                    idcardVerifyRequest.setAppid(appid);
                    idcardVerifyRequest.setAppSecret(appSecret);

                    //
                    //  JSONObject jsonObject = JSONObject.parseObject("{\"showapi_res_error\":\"\",\"showapi_res_code\":0,\"showapi_res_body\":{\"birthday\":\"1992-06-21\",\"ret_code\":0,\"sex\":\"M\",\"address\":\"湖南常德市桃源县\",\"code\":0,\"msg\":\"匹配\"}}");
                    // IdcardVerifyResponse idcardVerifyResponse = jsonObject.toJavaObject(jsonObject, IdcardVerifyResponse.class);
                    // IdcardVerifyResult result = idcardVerifyResponse.getResult();
                    // 2018/5/14  retCode !=0 ,验证通过，但是状态为未验证
                    IdcardVerifyResult result = iIdcardVerifyService.verify(idcardVerifyRequest);
                    if (!result.getCode().equals(0)) {
                        throw new BusinessException(PartyCode.PARAMETER_ILLEGAL, "身份证与姓名不匹配");
                    } else {
                        //存为已验证,改性别
                        member1.setIsCertified(1);
                        if (result.getSex().equals("M")) {
                            member1.setSex(1);
                            member.setSex(1);
                        } else {
                            member1.setSex(0);
                            member.setSex(0);
                        }
                        memberService.update(member1);
                    }
                }
            }

            gatherInfoMemberBizService.saveInsuranceInfo(currentUser.getId(), memberInfo, member);
            MemberOutput memberOutput = memberBizService.getLoginMember(memberService.get(currentUser.getId()));
            gatherInfoMemberBizService.addMember(projectId, currentUser.getId());
            String partnerId = null;

            try {
                // 机构成员所属
                PartnerMember partnerMember = new PartnerMember();
                partnerId = gatherInfoProjectService.get(projectId).getCreateBy();
                partnerMember.setPartnerId(partnerId);
                partnerMember.setMemberId(currentUser.getId());
                partnerMemberService.getSet(partnerMember);
            } catch (Exception e) {
                logger.error("保存关系异常", e);
            }

            try {
                // 个人统计表添加数据
                memberPersonalCountBizService.getSet(partnerId, currentUser.getId());
            } catch (Exception e) {
                logger.error("个人统计表添加数据异常", e);
            }

            return AjaxResult.success(memberOutput);

        } catch (BusinessException e) {
            AjaxResult ajaxResult = new AjaxResult();
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setErrorCode(e.getCode());
            ajaxResult.setDescription(e.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("保存保险信息失败", e);

            AjaxResult ajaxResult = new AjaxResult();
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setErrorCode(100);
            ajaxResult.setDescription("保存信息失败");
            return ajaxResult;
        }
    }

    /**
     * 获取信息
     *
     * @param projectId
     * @param request
     * @return
     * @throws Exception
     */
    @Authorization
    @ResponseBody
    @RequestMapping(value = "/getItineraryInfo")
    public AjaxResult getItineraryInfo(String projectId, HttpServletRequest request) throws Exception {
        // 数据验证
        if (Strings.isNullOrEmpty(projectId)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "项目主键不能为空");
        }
        GatherInfoProject gatherInfoProject = gatherInfoProjectService.get(projectId);
        if (null == gatherInfoProject || gatherInfoProject.getDelFlag().equals("1")) {
            return AjaxResult.error(PartyCode.IS_NO_DATA, "文章内容不存在");
        }
        try {
            Map<String, Object> map = gatherInfoMemberBizService.getItineraryInfo(projectId, request);
            AjaxResult ajaxResult = AjaxResult.success(map);
            tokenInterceptor.getToken(ajaxResult);
            return ajaxResult;
        } catch (Exception e) {
            logger.error("获取行程信息异常", e);
            return AjaxResult.error(100, "未知异常");
        }
    }

    /**
     * 行程信息收集
     *
     * @param memberInfo
     * @param member
     * @param input
     * @param request
     * @return
     */
    @SessionToken(verify = true)
    @ResponseBody
    @Authorization
    @RequestMapping(value = "/saveItineraryInfo", method = RequestMethod.POST)
    public AjaxResult saveItineraryInfo(GatherInfoMember memberInfo, Member member, GatherInfoMemberInput input, HttpServletRequest request) {
        try {
            CurrentUser currentUser = memberBizService.bindPhoneBiz2(member.getMobile(), input.getVerifyCode(), member.getCountryCode(), request);
            gatherInfoMemberBizService.saveItineraryInfo(currentUser.getId(), memberInfo, member);
            MemberOutput memberOutput = memberBizService.getLoginMember(memberService.get(currentUser.getId()));

            Member dbMember = memberService.get(currentUser.getId());
            if (null != dbMember.getIsCertified() && YesNoStatus.YES.getCode().equals(dbMember.getIsCertified())) {
                dbMember.setFullname(null);
            }
            dbMember.setCountryCode(member.getCountryCode());
            memberService.update(dbMember);
            String partnerId = null;

            try {
                // 机构成员所属
                PartnerMember partnerMember = new PartnerMember();
                partnerId = gatherInfoProjectService.get(memberInfo.getProjectId()).getCreateBy();
                partnerMember.setPartnerId(partnerId);
                partnerMember.setMemberId(currentUser.getId());
                partnerMemberService.getSet(partnerMember);
            } catch (Exception e) {
                logger.error("保存关系异常", e);
            }

            try {
                // 个人统计表添加数据
                memberPersonalCountBizService.getSet(partnerId, currentUser.getId());
            } catch (Exception e) {
                logger.error("个人统计表添加数据异常", e);
            }

            return AjaxResult.success(memberOutput);
        } catch (BusinessException e) {
            AjaxResult ajaxResult = new AjaxResult();
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setErrorCode(e.getCode());
            ajaxResult.setDescription(e.getMessage());
            return ajaxResult;
        } catch (Exception e) {
            logger.error("保存行程信息失败", e);

            AjaxResult ajaxResult = new AjaxResult();
            tokenInterceptor.getToken(ajaxResult);
            ajaxResult.setErrorCode(100);
            ajaxResult.setDescription("保存信息失败");
            return ajaxResult;
        }
    }
}
